package com.example.minefieldkeepercloud.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.example.minefieldkeepercloud.R;
import com.example.minefieldkeepercloud.adapter.LogAdapter;
import com.example.minefieldkeepercloud.bean.IPChangeBean;
import com.example.minefieldkeepercloud.bean.IpReportBean;
import com.example.minefieldkeepercloud.network.MyGson;
import com.example.minefieldkeepercloud.network.TcpNetHelper;

import com.example.minefieldkeepercloud.util.ToastUtil;
import com.example.minefieldkeepercloud.util.netty.INettyClient;
import com.example.minefieldkeepercloud.util.netty.NettyClient;
import com.example.minefieldkeepercloud.view.dialog.LoadingDialog;
import com.example.minefieldkeepercloud.view.lazyviewpager.LazyFragmentPagerAdapter;

/**
 * ip设置fragment  批量的
 * Created by Administrator on 2019/3/5.
 */

public class ManyIpSettingFragment extends Fragment implements LazyFragmentPagerAdapter.Laziable {

    private INettyClient.OnDataReceiveListener onDataReceiveListener;

    private LoadingDialog loadingDialog;
    private int isManyRequest = 3;//1开始 2暂停 3结束
    //当前ip
    @BindView(R.id.edit_a1)
    TextView edit_a1;
    @BindView(R.id.edit_a2)
    TextView edit_a2;
    @BindView(R.id.edit_a3)
    TextView edit_a3;
    @BindView(R.id.edit_a4)
    TextView edit_a4;

    //开始IP
    @BindView(R.id.edit_start1)
    EditText edit_start1;
    @BindView(R.id.edit_start2)
    EditText edit_start2;
    @BindView(R.id.edit_start3)
    EditText edit_start3;
    @BindView(R.id.edit_start4)
    EditText edit_start4;

    //结束IP
    @BindView(R.id.edit_end1)
    TextView edit_end1;
    @BindView(R.id.edit_end2)
    TextView edit_end2;
    @BindView(R.id.edit_end3)
    TextView edit_end3;
    @BindView(R.id.edit_end4)
    EditText edit_end4;


    //要修改ip
    @BindView(R.id.edit_b1)
    TextView edit_b1;
    @BindView(R.id.edit_b2)
    TextView edit_b2;
    @BindView(R.id.edit_b3)
    TextView edit_b3;
    @BindView(R.id.edit_b4)
    EditText edit_b4;

    //开始
    @BindView(R.id.btn_start)
    TextView btn_start;

    //结束
    @BindView(R.id.btn_end)
    TextView btn_end;
    //顶部布局
    @BindView(R.id.ll_top)
    LinearLayout ll_top;

    private boolean isStart = false;//是否开始


    @BindView(R.id.listview)
    ListView listView;
    private List<String> stringList;
    private LogAdapter logAdapter;


    private String reIP = "";//原来ip
    private String nowIP = "";//要修改的IP
    @OnClick({R.id.btn_start, R.id.btn_end})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_start://开始
                if (check()) {

                    logAdapter.additem("开始批量设置");
                    isStart = true;
                    edit_b4.setEnabled(false);
                    btn_start.setTextColor(getResources().getColor(R.color.black3));
                    btn_start.setBackgroundResource(R.drawable.btn_gary_bg);
                    ll_top.setVisibility(View.GONE);
                    edit_b1.setText("" + edit_start1.getText().toString().trim());
                    edit_b2.setText("" + edit_start2.getText().toString().trim());
                    edit_b3.setText("" + edit_start3.getText().toString().trim());
                    if (isManyRequest!=2)
                    {
                        edit_b4.setText("" + edit_start4.getText().toString().trim());
                    }
                    isManyRequest=1;


                }
                break;

            case R.id.btn_end://结束


                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("提示").setCancelable(false).setMessage("请选择暂停还是结束任务？").setNegativeButton("暂停", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            logAdapter.additem("暂停批量设置");
                            suspend();

                        }
                    }).setPositiveButton("结束", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                            stop();

                        }
                    });
                    builder.create().show();

                break;


        }
    }

    private boolean check() {

        //把为空的输入框变为0
        if ("".equals(edit_start1.getText().toString().trim())) {
            ToastUtil.showToast(getActivity(), "请填写开始IP");
            return false;
        }


        if ("".equals(edit_start2.getText().toString().trim())) {
            ToastUtil.showToast(getActivity(), "请填写开始IP");
            return false;
        }

        if ("".equals(edit_start3.getText().toString().trim())) {
            ToastUtil.showToast(getActivity(), "请填写开始IP");
            return false;
        }
        if ("".equals(edit_start4.getText().toString().trim())) {
            ToastUtil.showToast(getActivity(), "请填写开始IP");
            return false;
        }

        if ("".equals(edit_end4.getText().toString().trim())) {
            ToastUtil.showToast(getActivity(), "请填写结束IP");
            return false;
        }

        if ("".equals(edit_b4.getText().toString().trim())) {
            edit_b4.setText("0");
        }


//        =========================================================


        if (Integer.valueOf(edit_start1.getText().toString().trim()) > 255) {
            edit_start1.setText("" + 255);
            ToastUtil.showToast(getActivity(), "最大255");
            return false;
        }
        if (Integer.valueOf(edit_start2.getText().toString().trim()) > 255) {
            edit_start2.setText("" + 255);
            ToastUtil.showToast(getActivity(), "最大255");
            return false;
        }
        if (Integer.valueOf(edit_start3.getText().toString().trim()) > 255) {
            edit_start3.setText("" + 255);
            ToastUtil.showToast(getActivity(), "最大255");
            return false;
        }
        if (Integer.valueOf(edit_start4.getText().toString().trim()) > 255) {
            edit_start4.setText("" + 255);
            ToastUtil.showToast(getActivity(), "最大255");
            return false;
        }
        if (Integer.valueOf(edit_end4.getText().toString().trim()) > 255) {
            edit_end4.setText("" + 255);
            ToastUtil.showToast(getActivity(), "最大255");
            return false;
        }

        if (Integer.valueOf(edit_start4.getText().toString().trim()) > Integer.valueOf(edit_end4.getText().toString().trim())) {
            ToastUtil.showToast(getActivity(), "结束IP不能比开始IP小");
            return false;
        }
        return true;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_manyipsetting, container, false);
        ButterKnife.bind(this, view);
        loadingDialog = new LoadingDialog(getActivity(), 0);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setSetDataReceiveListener();
        initListview();
        initEdit();

    }

    /**
     * 初始化日志列表
     */
    private void initListview() {
        stringList=new ArrayList<>();
        logAdapter=new LogAdapter(stringList,getActivity());
        listView.setAdapter(logAdapter);


    }
    /**
     * 监听输入框 开始IP
     */
    private void initEdit() {
        edit_start1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length()!=0&&(charSequence.charAt(charSequence.length()-1)+"").equals("."))
                {
                    String substring = charSequence.toString().substring(0, charSequence.length() - 1);
                    edit_start1.setText(substring);
                    edit_start2.requestFocus();
                }
//                else if (charSequence.toString().length()==3)
//                {
//                    edit_start2.requestFocus();
//                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                edit_end1.setText(edit_start1.getText().toString().trim());
            }
        });

        edit_start2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length()!=0&&(charSequence.charAt(charSequence.length()-1)+"").equals("."))
                {
                    String substring = charSequence.toString().substring(0, charSequence.length() - 1);
                    edit_start2.setText(substring);
                    edit_start3.requestFocus();
                }
//                else if (charSequence.toString().length()==3)
//                {
//                    edit_start3.requestFocus();
//                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                edit_end2.setText(edit_start2.getText().toString().trim());
            }
        });

        edit_start3.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length()!=0&&(charSequence.charAt(charSequence.length()-1)+"").equals("."))
                {
                    String substring = charSequence.toString().substring(0, charSequence.length() - 1);
                    edit_start3.setText(substring);
                    edit_start4.requestFocus();
                }
//                else if (charSequence.toString().length()==3)
//                {
//                    edit_start4.requestFocus();
//                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                edit_end3.setText(edit_start3.getText().toString().trim());
            }
        });



        edit_start4.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!charSequence.toString().equals(""))
                {
                    if (Integer.valueOf(charSequence.toString())>254)
                    {
                        edit_end4.setText("255");
                    }else
                    {
                        edit_end4.setText(Integer.valueOf(charSequence.toString())+1+"");
                    }

                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


    }

//    private String nowMac = "";//临时储存的当前Mac



    private String[] macs={"","",""};//储存三个mac
    private int n=0;

    //当前mac是否在数组里
    private boolean isYes(String macAddress) {
        if (macAddress.equals(macs[0]))
        {
            return true;
        } if (macAddress.equals(macs[1]))
        {
            return true;
        }if (macAddress.equals(macs[2]))
        {
            return true;
        }
        return false;
    }

    /**
     * 设置数据监听
     */
    private void setSetDataReceiveListener() {
        onDataReceiveListener = new INettyClient.OnDataReceiveListener() {
            @Override
            public void onDataReceive(int mt, String jsons) {

//                loadingDialog.dismiss();
                Log.i("-->", "IpSettingFragment返回数据：" + mt + " json:" + jsons);

                //矿机发送IP信息
                if (mt == TcpNetHelper.IpReport && isStart) {
                    IpReportBean ipReportBean = MyGson.getInstance().fromJson(jsons, IpReportBean.class);

                    if (!isYes(ipReportBean.getMacAddress()))
                    {

//                    }
//                    if (!ipReportBean.getMacAddress().equals(nowMac)) {
                        logAdapter.additem("收到矿机发送的IP:"+ipReportBean.getIP());
//                        nowMac = ipReportBean.getMacAddress();
                         macs[n]=ipReportBean.getMacAddress();

                        String[] split = ipReportBean.getIP().toString().split("\\.");
                        if (split.length == 4) {
                            edit_a1.setText("" + split[0]);
                            edit_a2.setText("" + split[1]);
                            edit_a3.setText("" + split[2]);
                            edit_a4.setText("" + split[3]);

                            reIP =edit_a1.getText().toString().trim() + "." + edit_a2.getText().toString().trim() + "." + edit_a3.getText().toString().trim() + "." + edit_a4.getText().toString().trim();
                            nowIP= edit_b1.getText().toString().trim() + "." + edit_b2.getText().toString().trim() + "." + edit_b3.getText().toString().trim() + "." + edit_b4.getText().toString().trim();
                                    logAdapter.additem("正在修改IP"+reIP+"-->"+nowIP);
                            TcpNetHelper.changeIP(reIP, nowIP);
                                //每12秒只能请求一次


                            //发出请求 就将要修改的IP递增
                            int integer = Integer.valueOf(edit_b4.getText().toString().trim());
                            if (integer< Integer.valueOf(edit_end4.getText().toString().trim())&&integer < 255) {
                                edit_b4.setText(integer + 1 + "");
                            } else {
                                //到达最大值 停止接收Ip
                                isStart=false;

                            }
                                 final int i=n;
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {

                                        macs[i]="";
//                                        nowMac="";
                                    }
                                }, 12000);

                            n=(n+1)%3;


                        }
                    }
                }
                //修改IP结果
                if (mt == TcpNetHelper.ReChangeIP&&isManyRequest==1) {
                    IPChangeBean ipChangeBean = MyGson.getInstance().fromJson(jsons, IPChangeBean.class);
                    logAdapter.additem(ipChangeBean.getMessage()+ " "+reIP+"-->"+nowIP);

                    //到达最大值之后先返回值再停止
                    if (edit_end4.getText().toString().trim().equals(edit_b4.getText().toString().trim()))
                    {
                        ToastUtil.showToast(getActivity(), "已经到最大值了，自动结束");
                        stop();
                    }

                    if (ipChangeBean.isIsSuccess()) {
                        ToastUtil.showToast(getActivity(), "" + ipChangeBean.getMessage());
                        edit_a1.setText("0");
                        edit_a2.setText("0");
                        edit_a3.setText("0");
                        edit_a4.setText("0");

                    } else {
                        ToastUtil.showToast(getActivity(), "" + ipChangeBean.getMessage());
                    }
                }


            }
        };
        if (onDataReceiveListener != null)
            NettyClient.getInstance().addDataReceiveListener(onDataReceiveListener);
    }


    /**
     * 停止
     */
    private void stop() {
        isStart = false;
        isManyRequest=3;
        logAdapter.additem("结束批量设置");
        btn_start.setTextColor(getResources().getColor(R.color.white));
        btn_start.setBackgroundResource(R.drawable.btn_system_bg);
        ll_top.setVisibility(View.VISIBLE);

        edit_a1.setText("0");
        edit_a2.setText("0");
        edit_a3.setText("0");
        edit_a4.setText("0");

        edit_b1.setText("0");
        edit_b2.setText("0");
        edit_b3.setText("0");
        edit_b4.setText("0");

        edit_start1.setText("");
        edit_start2.setText("");
        edit_start3.setText("");
        edit_start4.setText("");




        edit_end1.setText("0");
        edit_end2.setText("0");
        edit_end3.setText("0");
        edit_end4.setText("0");

        edit_a4.setEnabled(false);
    }

    /**
     * 暂停
     */
    private void suspend() {
        isStart = false;
        isManyRequest=2;
        btn_start.setTextColor(getResources().getColor(R.color.white));
        btn_start.setBackgroundResource(R.drawable.btn_system_bg);

        edit_a1.setText("0");
        edit_a2.setText("0");
        edit_a3.setText("0");
        edit_a4.setText("0");


        edit_b4.setEnabled(true);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //解除绑定
        NettyClient.getInstance().delectDataReceiveListener(onDataReceiveListener);
    }
}
